/*
 * Configuracion.cpp
 *
 *  Created on: 30/10/2011
 *      Author: diego
 */

#include "Configuracion.h"

Configuracion* Configuracion::cnf = NULL;

static Configuracion* Configuracion::getConf(string path_conf){
	if (Configuracion::cnf == NULL){
		Configuracion::cnf = new Configuracion(path_conf);
		return Configuracion::cnf;
	}else{
		return Configuracion::cnf;
	}
}

static void Configuracion::deleteConf(){
	if (Configuracion::cnf != NULL){
		delete Configuracion::cnf;
		Configuracion::cnf = NULL;
	}
}

Configuracion::Configuracion(string path_conf) {
	this->conf = new ifstream();
	this->conf->open(path_conf.c_str());

	if (!this->conf->good()) {
		cout << "Error al abrir el archivo de indexacion";
		exit(1);
	}

	string atributo;
	string valor;
	char charLeido = 1;

	bool leoAtributo = true;

	(*this->conf) >> noskipws >> charLeido;
	while (!this->conf->eof()) {

		if (charLeido != '#'){
			if (charLeido != ' '){

				if (leoAtributo){
					if (charLeido != '=' && charLeido != '\n'){
						atributo += charLeido;
					}else{
						leoAtributo = false;
					}
				}else{
					if (charLeido != '\n'){
						valor += charLeido;
					}else{
						this->procesarParametro(atributo, valor);
						atributo.clear();
						valor.clear();
						leoAtributo = true;
					}
				}
			}

			(*this->conf) >> noskipws >> charLeido;
		}else{
			// entre en un comentario
			while (!this->conf->eof() && charLeido != '\n') {
				(*this->conf) >> noskipws >> charLeido;
			}
			(*this->conf) >> noskipws >> charLeido;
			leoAtributo = true;
		}
	}

	this->conf->close();
}

void Configuracion::procesarParametro(string atributo, string valor){
	if (atributo == "max_mem_indexador"){
		this->var_max_mem_indexador = this->str2int(valor);
	}else if (atributo == "front_coding"){
		this->var_front_coding = this->str2int(valor);
	}else if (atributo == "path_indice"){
		this->var_path_indice = valor;
	}else if (atributo == "path_indice_documentos"){
		this->var_path_documentos = valor;
	}else if (atributo == "path_indice_stopwords"){
		this->var_path_stopwords = valor;
	}else if (atributo == "host_addr"){
		this->var_host_addr = valor;
	}else if (atributo == "port_number"){
		this->var_port_number = this->str2int(valor);
	}

	return;
}

int Configuracion::str2int(string str) {
	stringstream ss(str);
	int n;
	ss >> n;
	return n;
}

int Configuracion::max_mem_indexdor(){
	return this->var_max_mem_indexador;
}

string Configuracion::path_indice(){
	return this->var_path_indice;
}

int Configuracion::front_coding(){
	return this->var_front_coding;
}

string Configuracion::path_documentos(){
	return this->var_path_documentos;
}

string Configuracion::path_stopwords(){
	return this->var_path_stopwords;
}

string Configuracion::host_addr(){
	return this->var_host_addr;
}

int Configuracion::port_number(){
	return this->var_port_number;
}

Configuracion::~Configuracion() {
	delete this->conf;
}

